package AIO;

import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;

/**
 * @author fei.fang
 * @date 2021/8/24
 **/
public class ChannelHandler implements CompletionHandler<Integer, Attachment> {
    @Override
    public void completed(Integer result, Attachment attachment) {
        if (attachment.isReadMode()) {
            ByteBuffer buffer = attachment.getBuffer();
            buffer.flip();
            byte[] bytes = new byte[buffer.limit()];
            buffer.get(bytes);
            String msg = new String(buffer.array()).trim();
            System.out.println("收到客户端数据：" + msg);

            buffer.clear();
            buffer.put("Response".getBytes(StandardCharsets.UTF_8));
            attachment.setReadMode(false);
            buffer.flip();
            attachment.getChannel().write(buffer, attachment, this);
        }else{
            attachment.setReadMode(true);
            attachment.getBuffer().clear();
            attachment.getChannel().read(attachment.getBuffer(), attachment, this);
        }
    }

    @Override
    public void failed(Throwable exc, Attachment attachment) {
        System.out.println("连接断开");
    }
}
